<?php

namespace App\Console\Commands;

use App\DataProviders\AirportDataProviderInterface;
use App\Services\SearchIndexServiceInterface;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class UpdateAirportsIndex extends Command
{
    protected $signature = 'update-airports-index';
    private const AIRPORTS = 'airports';

    public function __construct(
        private readonly SearchIndexServiceInterface $searchIndexService,
        private readonly AirportDataProviderInterface $airportsLoaderService
    ) {
        parent::__construct();
    }

    public function handle(): void
    {
        try {
            if ($this->searchIndexService->indexExists(self::AIRPORTS)) {
                $this->searchIndexService->deleteIndex(self::AIRPORTS);
            }

            Cache::flush();

            $airports = $this->airportsLoaderService->fetchAirportsData();
            $bar = $this->output->createProgressBar(count($airports));

            foreach ($airports as $code => $airport) {
                $this->searchIndexService->createIndex(self::AIRPORTS, $code, $airport);
                $bar->advance();
            }
            $bar->finish();

            $this->info("\nAirports index has been updated successfully!");
        } catch (\Throwable $e) {
            $this->error("An unexpected error occurred: " . $e->getMessage());
        }
    }
}
